<template>
	<div class="hom_game_box">
		<div v-for="(item, index) in homeGameData" :key="index">
			<div class="card_list_box game_list_box" v-if="item">
				<ul class="card_title">
					<li class="title_left">
						<img :key="item.id == 0 ? item.id : item.icon_h5"
							:src="item.id == 0 ? `/imgs/home/${item.id}.webp` : joinURL(settings.backend_upload, item.icon_h5)"
							alt="" />
						<span> {{ unserialize(item.name, false) }}</span>
					</li>
					<li class="title_right">
						<p class="more" @click="clickGameMore(item)">
							{{ t('home_page_more') }}
						</p>
						<div class="swiper-btn" :class="['swiper_pre_game' + index, { disabled: !currentIndex[index] }]"
							@click="handlePrev(index)">
							<iconpark-icon name="zuo-keyong" size="30" />
						</div>
						{{}}
						<div class="swiper-btn"
							:class="['swiper_next_game' + index, { disabled: (currentIndex[index] || 0) == item.newList.length - 1 }]"
							@click="handleNext(index)">
							<iconpark-icon name="you-keyong" size="30" />
						</div>
					</li>
				</ul>
				<div ref="swiperConRef" class="pk_swiper-container" @touchstart="onTouchStart($event, index)"
					@touchmove="onTouchMove($event, index)" @touchend="onTouchEnd($event, index)"
					@mousedown="onMouseDown($event, index)" @mousemove="onMouseMove($event, index)"
					@mouseup="onMouseUp($event, index)" @mouseleave="onMouseUp($event, index)">
					<div class="pk_swiper-wrapper" :style="getWrapperStyle(index)">
						<div :style="{ minHeight: swiperHeight(index) }" class="swiper-slide"
							v-for="(gameList, i) in item.newList" :key="i">
							<div :class="item.id == 0 ? 'hot_game_list' : 'other_list'">
								<div :class="item.id == 0 ? 'all_game' : 'other_game'" v-for="(gameItem, s) in gameList"
									:key="s">
									<div @click="toGameDetail(gameItem)" class="unready">
										<img class="bg_img" src="@/assets/img-default.svg" :data-ready="imgReady"
											v-thumb="`${joinURL(settings.backend_upload, gameItem.picture_h5)}`"
											:key="gameItem.picture_h5" alt="" />
										<iconpark-icon class="collect_img" v-if="isLocalLoggedIn"
											:name="allCollected.includes(gameItem.id) ? 'shoucang-sel' : 'shoucang-def'"
											size="1rem"
											@click.stop="reqCollect(gameItem, allCollected)"></iconpark-icon>
										<div class="game_name">
											{{ unserialize(gameItem.name, false) }}
										</div>
									</div>
									<div v-if="gameItem.ismMintain === 1 || gameItem.is_maintain === 1"
										class="masking_layer">
										<iconpark-icon class="maskin_img" name="padlock1" size="28" />
										<span>{{ t('inside_page_game_coming_soon') }}</span>
										<span>{{ t('inside_page_game_stay_tuned') }}</span>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { storeToRefs } from 'pinia';
import pinia from '@/store/index';
import { useI18n } from 'vue-i18n';
import { joinURL } from '@/utils/publicMethods'


// 手写swiper
const startX = ref(0);
const currentX = ref(0);
const isDragging = ref(false);
const isDraggingIndex = ref(0)
const swiperConRef = ref()
const currentIndex: any = ref([]);
// 判断纵向滚动
const startY = ref(0);
const isHorizontalDrag = ref(false);
const getWrapperStyle = (index: any) => {
	return [
		{
			transform: isDraggingIndex.value == index ? `translateX(calc(-${(currentIndex.value[index] || 0) * 100}% + ${isDragging.value ? currentX.value - startX.value : 0}px))` : `translateX(-${(currentIndex.value[index] || 0) * 100}%)`,
			transition: isDragging.value ? 'none' : 'transform 0.3s ease'
		}
	]
}
// 触摸/鼠标事件处理
const onTouchStart = (e: any, index: any) => {
	isDraggingIndex.value = index
	startX.value = e.touches[0].clientX;
	startY.value = e.touches[0].clientY;
	currentX.value = startX.value;
	isDragging.value = true;
	isHorizontalDrag.value = false;
};

const onTouchMove = (e: any, index: any) => {
	isDraggingIndex.value = index
	if (!isDragging.value) return;
	const currentXPos = e.touches[0].clientX;
	const currentYPos = e.touches[0].clientY;
	// 如果是第一次移动，判断是水平还是垂直
	if (!isHorizontalDrag.value) {
		const dx = Math.abs(currentXPos - startX.value);
		const dy = Math.abs(currentYPos - startY.value);

		// 如果水平移动距离大于垂直移动距离，则认为是水平滑动
		if (dx > dy) {
			isHorizontalDrag.value = true;
			e.preventDefault(); // 只有水平滑动时才阻止默认行为
		} else {
			// 垂直滚动，不处理，允许父元素滚动
			isDragging.value = false;
			return;
		}
	} else {
		e.preventDefault(); // 水平滑动时阻止默认行为
	}

	currentX.value = currentXPos;
};

const onTouchEnd = (e: any, index: any) => {
	if (!isDragging.value) return;
	handleDragEnd(index);
	if (e) return
};

const onMouseDown = (e: any, index: any) => {
	isDraggingIndex.value = index
	startX.value = e.clientX;
	startY.value = e.clientY;
	currentX.value = startX.value;
	isDragging.value = true;
	document.body.style.cursor = 'grabbing';
	isHorizontalDrag.value = false;
};

const onMouseMove = (e: any, index: any) => {
	isDraggingIndex.value = index
	if (!isDragging.value) return;

	const currentXPos = e.clientX;
	const currentYPos = e.clientY;

	if (!isHorizontalDrag.value) {
		const dx = Math.abs(currentXPos - startX.value);
		const dy = Math.abs(currentYPos - startY.value);

		if (dx > dy) {
			isHorizontalDrag.value = true;
		} else {
			isDragging.value = false;
			document.body.style.cursor = '';
			return;
		}
	}

	currentX.value = currentXPos;
};

const onMouseUp = (e: any, index: any) => {
	if (!isDragging.value) return;
	handleDragEnd(index);
	document.body.style.cursor = '';
	if (e) return
};

const handleDragEnd = (index: any) => {
	const deltaX = currentX.value - startX.value;
	const containerWidth = swiperConRef.value[index].clientWidth;
	const ratio = Math.abs(deltaX) / containerWidth;
	if (ratio > 0.3) {
		if (deltaX > 0) {
			handlePrev(index);
		} else {
			handleNext(index);
		}
	}

	isDragging.value = false;
};



import { useRouter } from 'vue-router';
const router = useRouter();
import { User } from '@/store/user';
import { Page } from '@/store/page';

import { reqCollect } from '@/utils/useNetMethods';
import { unserialize, onPlayGame } from '@/utils/useStoreMethods';
const { isLocalLoggedIn, allCollected } = storeToRefs(User(pinia));
const { lang, settings, homeGameData } = storeToRefs(Page(pinia));

const { t } = useI18n();


const imgReady = (el: any) => {
	setTimeout(() => {
		try {
			el.parentElement.className = 'ready'
		} catch { }
	}, 0)
}

const refNameList: any = ref([]);

const clickGameMore = (item: any) => {
	// if (item.id == 0) {
	//   Page(pinia).setGameIsLoading(true);
	//   setTimeout(() => {
	//     router.push('/hotGameDetail')
	//   },200)
	// } else {
	//   Local.set('homePageData', item)
	//   setTimeout(() => {
	//     eventBus.emit('setCateVal', item)
	//   }, 50)
	// }
	router.push({
		path: '/categoryPage',
		query: {
			type: item.id,
		},
	});
};

const swiperHeight = (index: number) => {
	return refNameList.value[index]?.height + 'px';
};

const handlePrev = (index: number) => {
	if (currentIndex.value[index]) {
		currentIndex.value[index]--
	} else {
		currentIndex.value[index] = 0
	}
};

const handleNext = (index: number) => {
	console.error(currentIndex.value[index], (homeGameData.value[index].newList.length - 1))
	if ((currentIndex.value[index] || 0) < (homeGameData.value[index].newList.length - 1)) {
		if (!currentIndex.value[index]) currentIndex.value[index] = 0
		currentIndex.value[index]++
	} else {
		currentIndex.value[index] = (homeGameData.value[index].newList.length - 1)
	}
};



// 判读是否是进入游戏二级页或者直接进入游戏
const toGameDetail = async (item: any) => {
	if (item.has_next == 1 && item.three_game_kind?.length) {
		// 跳转二级页面
		router.push({
			path: 'gameDetail',
			query: {
				agent_id: item.id,
				venue_id: item.three_game_kind[0].id,
				name: item.name[lang.value].toUpperCase(),
			},
		});
	} else {
		onPlayGame(item);
	}
};


</script>

<style lang="scss" scoped>
.game_list_box {
	:deep(.swiper-backface-hidden .swiper-slide) {
		width: 97%;
	}

	:deep(.swiper-wrapper) {
		margin-left: -4px;
	}
}

.card_list_box {
	padding-left: 14px;

	.card_title {
		display: flex;
		padding: 12px 14px 12px 0;
		justify-content: space-between;
		align-items: center;
		// height: 24px;
		line-height: 24px;

		.title_left {
			font-family: PingFang SC;
			font-size: 14px;
			font-weight: 600;
			line-height: 16px;
			text-align: left;
			color: #fcfffa;
			display: flex;
			justify-content: space-between;
			align-items: center;

			img {
				width: 18px;
				height: 18px;
				margin-right: 5px;
			}
		}

		.title_right {
			font-family: PingFang SC;
			font-size: 12px;
			font-weight: 500;
			color: #c6c4f5;
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 24px;

			.more {
				background: #282747;
				// margin-left: 8px;
				// height: 100%;
				line-height: 24px;
				padding: 0px 6px;
				border-radius: 6px;
				box-shadow: 0.5px 0.5px 1px 0px #4B4A6E inset;
			}

			.swiper-btn {
				position: relative;
				top: 4px;
				margin-left: 8px;
			}

			.disabled {
				pointer-events: none;
				opacity: 0.5;
				cursor: not-allowed;
			}
		}
	}

	.hot_game_list {
		// height: 224px;
		width: 100%;
		display: flex;
		flex-wrap: wrap;
		// justify-content: space-between;

		.all_game {
			width: 81px;
			height: 108px;
			margin-right: 6px;
			margin-bottom: 6px;
			background: #1a1944;
			border-radius: 8px;
			position: relative;

			.bg_img {
				width: 82px;
				height: 82px;
			}

			.game_name {
				width: 100%;
				height: 26px;
				text-align: center;
				transform: translateY(-8px);
				color: #fff;
				font-size: 12px;
				line-height: 1;
				overflow: hidden;
				word-break: break-word;
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;
			}
		}
	}

	.other_list {
		width: 100%;
		// height: 304px;
		display: flex;
		flex-wrap: wrap;

		.other_game {
			position: relative;
			width: 110px;
			height: 146px;
			margin-right: 6px;
			margin-bottom: 6px;
			background: #1a1944;
			border-radius: 8px;
		}

		.bg_img {
			width: 110px;
			height: 110px;
			border-radius: 8px 8px 0 0;
			object-fit: cover;
		}

		.game_name {
			margin-top: 5px;
			width: 100%;
			height: 26px;
			text-align: center;
			transform: translateY(-8px);
			color: #fff;
			font-size: 12px;
			line-height: 1;
			overflow: hidden;
			word-break: break-word;
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
		}
	}

	.unready {
		opacity: 0.5;
	}

	.ready {
		opacity: 1;
	}

	.collect_img {
		position: absolute;
		top: 4px;
		right: 4px;
	}

	.masking_layer {
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
		left: 0;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		backdrop-filter: blur(1px);
		background: rgba(0, 0, 0, 0.6);
		font-family: PingFang SC;
		font-size: 12px;
		font-weight: 500;
		line-height: 18px;
		color: #ffffff;

		.maskin_img {
			width: 32px;
			height: 32px;
			margin-bottom: 8px;
		}
	}
}
</style>
